package com.example.demo.thread.Java线程间的通信;

public class volatile实现信号量 {


    private static volatile Integer i = 0;

    static class thread1 implements Runnable {
        @Override
        public void run() {
            synchronized (i) {
                while (i < 5) {
                    if (i % 2 == 0) {
                        System.out.println("thread1" + i);
                        i++;
                    }
                }
            }
        }
    }

    static class thread2 implements Runnable {
        @Override
        public void run() {
            synchronized (i) {
                while (i < 5) {
                    if (i % 2 == 1) {
                        System.out.println("thread2" + i);
                        i++;
                    }
                }
            }
        }

    }

    public static void main(String[] args) throws Exception {
        Thread t1 = new Thread(new thread1());
        Thread t2 = new Thread(new thread2());
        t1.start();
        Thread.sleep(1000);
        t2.start();
    }
}
